import React, { useEffect, useState, useMemo } from 'react';
import { withRouter } from 'umi';
import { Form, Collapse, Icon, Table, Input, Spin, message, Col } from 'antd';
import AutoRenderComponent from '@/pages/WorkFlow/components/FormControls/components/AutoRenderComponent/AutoRenderComponent';
import FunctionDescribe from '@/components/NewFunction/FunctionDescribe';
import { getPostApplyData } from '@/pages/WorkFlow/services';
import { removeEmptyChildren, findValueInTree } from '@/utils/tree';
import { GroupLabel } from '@/pages/Setting/Privilege/components/TreeSelectGroupRoleForPrivilege';
import { fetchManageList } from '@/pages/Setting/Privilege/services';
import Difference from '@/pages/WorkFlow/components/FormControls/components/Difference';
import { useRequest } from '@/hooks';
import { FUNCTION_TYPE, ORGANIZATIONAL_SCOPE, ADMINISTRATIVE_SCOPE, FUNCTION_GRADE } from './constants';
import { filterSoftwarePlatform, findHighestFunctionGrade } from './utils';
import styles from './index.less';

const LabelValue = ({ label, value, children, flexCenter }) => (
    <div className={styles.labelAndValueWrapper} style={{ alignItems: flexCenter ? 'center' : 'initial' }}>
        <Col span={4}>
            <div style={{ textAlign: 'right' }}>{label}：</div>
        </Col>
        <Col span={12}>
            {value ? (
                <span
                    // eslint-disable-next-line react/no-danger
                    dangerouslySetInnerHTML={{
                        __html: value === '' ? '-' : value?.replace(/[\r\n]+/g, '<br />')
                    }}
                />
            ) : (
                <div style={{ display: 'inline-block', minWidth: 120 }}>{children || '-'}</div>
            )}
        </Col>
    </div>
);

const NewFunction = ({ dataSource, form, formValueMap = {}, location }) => {
    const [approveDataLoading, setApproveDataLoading] = useState(false);
    const [approveData, setApproveData] = useState({});
    const { tenantResourceNewFunctionVO: detail = {}, compareDataField = {}, oldBusinessData = {} } = approveData;

    const { getFieldDecorator } = form;
    const { children: list = [] } = dataSource;
    const { query } = location;
    const hiDataId = query?.hiDataId ? query?.hiDataId : formValueMap?.hiDataId;

    const { data: manageList } = useRequest(fetchManageList);

    const existDifference = (resourceCode, field) => {
        const difference = compareDataField[resourceCode];
        if (!difference) {
            return { hasDifference: false, differenceValue: null };
        }
        const result = difference.updateFieldNames.includes(field);
        if (result) {
            const { tenantResourceNewFunctionVO = {} } = oldBusinessData;
            const olderValue = findValueInTree([tenantResourceNewFunctionVO], 'code', resourceCode);
            return { hasDifference: true, differenceValue: olderValue ? olderValue[field] : null };
        }
        return { hasDifference: false, differenceValue: null };
    };

    const columns = [
        {
            title: '功能',
            dataIndex: 'nameZh',
            width: 300
        },
        {
            title: '类型',
            dataIndex: 'type',
            width: 150,
            render: value => <span>{FUNCTION_TYPE[value]}</span>
        },
        {
            title: '状态',
            dataIndex: 'isEnable',
            width: 150,
            render: (value, record) => {
                const { hasDifference, differenceValue } = existDifference(record.code, 'isEnable');
                let difMsg = '';

                if (hasDifference) {
                    difMsg = differenceValue ? '已启用' : '已禁用';
                }

                return (
                    <Difference tip={hasDifference ? difMsg : undefined}>
                        <span style={{ paddingLeft: hasDifference ? 10 : 0, paddingRight: hasDifference ? 10 : 0 }}>
                            {value ? '已启用' : '已禁用'}
                        </span>
                    </Difference>
                );
            }
        },
        {
            title: '等级',
            width: 200,
            dataIndex: 'functionGrade',
            render: (value, record) => {
                const { hasDifference, differenceValue } = existDifference(record.code, 'functionGrade');
                const difMsg = hasDifference ? FUNCTION_GRADE[differenceValue] : '';

                return (
                    <Difference tip={hasDifference ? difMsg : undefined}>
                        <span
                            style={{ paddingLeft: hasDifference ? 10 : 0, paddingRight: hasDifference ? 10 : 0 }}
                            className={`functionGrade-${value}`}
                        >
                            {FUNCTION_GRADE[value]}
                        </span>
                    </Difference>
                );
            }
        },
        {
            title: () => (
                <div className={styles.newFunctionTableHeader}>
                    <div>业务端实现情况</div>
                    <ul>
                        <li>Web端</li>
                        <li>APP端</li>
                        <li>PC端</li>
                    </ul>
                </div>
            ),
            dataIndex: 'terminalScope',
            width: 200,
            render: (value = {}) => {
                const { WEB, APP, PC } = value;
                return (
                    <div className={styles.functionIncidenceWrapper}>
                        {WEB ? <Icon type="check" /> : <span>-</span>}
                        {APP ? <Icon type="check" /> : <span>-</span>}
                        {PC ? <Icon type="check" /> : <span>-</span>}
                    </div>
                );
            }
        },
        {
            title: '授权模板',
            dataIndex: 'roleCodes',
            render: (value, record) => {
                const { differenceValue } = existDifference(record.code, 'roleCodes');
                return (
                    <GroupLabel
                        title="授权情况"
                        data={manageList?.data || []}
                        oldValue={differenceValue || []}
                        value={value}
                    />
                );
            }
        }
    ];

    const differenceIsEnable = useMemo(() => {
        const { code } = detail;

        const { hasDifference, differenceValue } = existDifference(code, 'isEnable');
        let difMsg;

        if (hasDifference) {
            difMsg = differenceValue ? '已启用' : '已禁用';
        }

        return difMsg;
    }, [detail]);

    useEffect(() => {
        if (hiDataId) {
            const fetchApproveData = async () => {
                setApproveDataLoading(true);
                const { msg, code, data } = await getPostApplyData(hiDataId);
                if (code === 10000) {
                    setApproveData(data);
                } else {
                    message.error(msg);
                }
                setApproveDataLoading(false);
            };
            fetchApproveData();
        }
    }, [hiDataId]);

    return (
        <React.Fragment>
            <div className={styles.newFunctionWrapper}>
                <Spin spinning={approveDataLoading}>
                    <Form.Item style={{ display: 'none' }}>
                        {getFieldDecorator('hiDataId', {
                            initialValue: hiDataId
                        })(<Input />)}
                    </Form.Item>
                    <FunctionDescribe
                        title={detail.nameZh}
                        describe={detail.onlineRemarkZh}
                        releaseTime={detail.onlineTime}
                    />
                    <Collapse
                        className={styles.collapsePanel}
                        bordered={false}
                        expandIconPosition="right"
                        defaultActiveKey={['newFunctionApplyReason', 'newFunctionApplyDetail', 'newFunctionApplyTree']}
                        expandIcon={panelProps => {
                            const { isActive } = panelProps;
                            return (
                                <div className={styles.collapseExpandIcon}>
                                    {isActive ? '收起' : '展开'}
                                    {isActive ? <Icon type="caret-up" /> : <Icon type="caret-down" />}
                                </div>
                            );
                        }}
                    >
                        <Collapse.Panel header="申请原因" key="newFunctionApplyReason">
                            <div className={styles.functionApplyReason}>
                                {Array.isArray(list) &&
                                    list.map(item => {
                                        const { label, formId, rules, extra } = item;

                                        let { initialValue } = item;

                                        if (formId === 'functionGrade') {
                                            initialValue = findHighestFunctionGrade([detail]);
                                        }

                                        if (formId === 'newFunctionName') {
                                            initialValue = detail.nameZh;
                                        }

                                        if (formId === 'newFunctionType') {
                                            initialValue = FUNCTION_TYPE[detail.type];
                                        }

                                        return (
                                            <Form.Item
                                                label={label}
                                                key={formId}
                                                extra={extra}
                                                style={{ display: item?.inRenderDom === false ? 'none' : 'block' }}
                                            >
                                                {getFieldDecorator(formId, {
                                                    initialValue,
                                                    rules
                                                })(<AutoRenderComponent form={form} config={item} />)}
                                            </Form.Item>
                                        );
                                    })}
                            </div>
                        </Collapse.Panel>
                        <Collapse.Panel header="功能详情" key="newFunctionApplyDetail">
                            <div className={styles.functionDescribeList}>
                                <LabelValue label="功能中文名称" value={detail.nameZh} />
                                <LabelValue label="功能英文名称" value={detail.nameEn} />
                                <LabelValue label="功能类型" value={FUNCTION_TYPE[detail.type]} />
                                <LabelValue label="从属功能" value={detail.parentNameZh} />
                                <LabelValue label="模块简介（中文）" value={detail.remarkZh} />
                                <LabelValue label="模块简介（英文）" value={detail.remarkEn} />
                                <LabelValue
                                    label="业务端实现情况"
                                    value={filterSoftwarePlatform(detail.terminalScope)}
                                />
                                <LabelValue label="初始等级" value={FUNCTION_GRADE[detail.functionGrade]} />
                                {detail?.type === 1 && (
                                    <LabelValue
                                        label="初始数据权限"
                                        value={`行政机构：${ADMINISTRATIVE_SCOPE[detail.defaultAdministrativeScope] ||
                                            ''}<br />组织机构：${ORGANIZATIONAL_SCOPE[
                                            detail.defaultOrganizationalScope
                                        ] || ''}`}
                                    />
                                )}
                            </div>
                        </Collapse.Panel>
                        <Collapse.Panel header="功能配置" key="newFunctionApplyTree">
                            <div className={styles.functionList}>
                                <LabelValue label="是否开启" flexCenter={differenceIsEnable}>
                                    <Difference tip={differenceIsEnable}>
                                        <span style={{ paddingLeft: differenceIsEnable ? 8 : 0 }}>
                                            {approveData?.isEnable ? '已启用' : '未启用'}
                                        </span>
                                    </Difference>
                                </LabelValue>
                                {approveData?.isEnable && (
                                    <Table
                                        className={styles.functionListTable}
                                        columns={columns}
                                        pagination={false}
                                        dataSource={removeEmptyChildren([detail])}
                                        expandIcon={({ expanded, onExpand, record }) => {
                                            const { children } = record;
                                            if (!children) {
                                                return <span style={{ width: 14, height: 14 }}></span>;
                                            }
                                            return expanded ? (
                                                <Icon
                                                    type="caret-down"
                                                    style={{ marginRight: 5 }}
                                                    onClick={e => onExpand(record, e)}
                                                />
                                            ) : (
                                                <Icon
                                                    type="caret-right"
                                                    style={{ marginRight: 5 }}
                                                    onClick={e => onExpand(record, e)}
                                                />
                                            );
                                        }}
                                    />
                                )}
                            </div>
                        </Collapse.Panel>
                    </Collapse>
                </Spin>
            </div>
        </React.Fragment>
    );
};
export default withRouter(NewFunction);
